﻿using System.Globalization;
using System.Linq;
using System.IO;
using MediaFS.Data;

namespace DokanNetMirror.MemoryFS
{
    public static class UtilityMethods
    {
        internal static bool Exists(this MemoryItem item)
        {
            return item != null;
        }

        public static string GetPathPart(this string sourcePath)
        {            
            return sourcePath.Substring(0, sourcePath.LastIndexOf('\\'));
        }

        public static string GetFilenamePart(this string sourcePath)
        {
            return sourcePath.Substring(sourcePath.LastIndexOf('\\') + 1);
        }

        public static char GetFirstAvailableDriveLetter()
        {
            // these are the driveletters that are in use;
            var usedDriveLetters =
                from drive
                in DriveInfo.GetDrives()
                select drive.Name.ToUpperInvariant()[0];

            // these are all possible driveletters [D..Z] that
            // we can choose from (don't want "B" as drive);
            var allDrives = string.Empty;
            for (var c = 'D'; c < 'Z'; c++)
                allDrives += c.ToString(CultureInfo.InvariantCulture);

            // these are the ones that are available;
            var availableDriveLetters = allDrives.Except(usedDriveLetters);

            if (!availableDriveLetters.Any())
                throw new DriveNotFoundException("No drives available!");

            return availableDriveLetters.First();
        }
    }
}
